//
//  StraightSection.m
//  Racing
//
//  Created by vy phan on 4/13/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "StraightSection.h"


@implementation StraightSection
-(id) initWithVertical:(bool)isVertical_ X:(int)x Y:(int)y
{
	self = [super initWithX:x Y:y];
	self->type = STRAIGHT;
	if (self != nil) {
		self->vertical = isVertical_;
	}
	return self;
}
-(bool) isVertical
{
	return self->vertical;
}
-(int) type
{
	return STRAIGHT;
}
-(BOOL) intersects:(Vehicle*)vehicle State:(State*)state
{
	Rectangle* bounds = [self getBounds];
	for ( int i = 0; i < state->numpoints; i++ ) {
		float x = [[state->xpoints objectAtIndex:i] floatValue];
		float y = [[state->ypoints objectAtIndex:i] floatValue];
		if ( [bounds contains:(int)x Y:(int)y] ) {
			return YES;
		}
	}
	return NO;
}
-(void) checkCollision:(Vehicle*)vehicle State:(State*)state
{
	if (vertical) {
		Rectangle *bounds = [self getBounds];
		for ( int i = 0; i < state->numpoints; i++ ) {
			float x = [[state->xpoints objectAtIndex:i] floatValue];
			float y = [[state->ypoints objectAtIndex:i] floatValue];
			
			if ( x <= [bounds x] ) {
				[state collide:x Y:y NX:1 NY:0];//.collide( x, y, 1, 0 );
			}
			if ( x >= ([bounds x] + [bounds width]) ) {
				[state collide:x Y:y NX:-1 NY:0];//state.collide( x, y, -1, 0 );
			}
		}
	}
	else {
		Rectangle *bounds = [self getBounds];
		for ( int i = 0; i < state->numpoints; i++ ) {
			float x = [[state->xpoints objectAtIndex:i] floatValue];
			float y = [[state->ypoints objectAtIndex:i] floatValue];
			if ( x <= [bounds x] ) {
				[state collide:x Y:y NX:0 NY:1];//.collide( x, y, 1, 0 );
			}
			if ( x >= ([bounds x] + [bounds width]) ) {
				[state collide:x Y:y NX:0 NY:-1];//state.collide( x, y, -1, 0 );
			}
		}
	}
}

-(float) distanceToEnd:(Vehicle*)vehicle
{
	Section *next = [self getNextSection];
	Rectangle *nextBounds = [next getBounds];
	Rectangle *bounds = [self getBounds];
	State *state = [vehicle currentState];
	
	if ( vertical ) {
		int y = [nextBounds y] > [bounds y]? [bounds y] : [bounds y] + [bounds height];
		float dist = y - state->y;
		if ( dist < 0 ) dist = -dist;
		return dist;
	}
	else {
		int x = [nextBounds x] > [bounds x]? [bounds x] : [bounds x] + [bounds width];
		float dist = x - state->x;
		if ( dist < 0 ) dist = -dist;
		return dist;
	}
}
@end
